<?php


namespace app\admin\authentication;

use app\lib\enum\JwtEnum;
use app\lib\exception\admin\AuthenticationException;
use \Firebase\JWT\JWT as JWTS;

class Jwt
{
    //加密用的 盐
    private $key = JwtEnum::KEY;
    //签发者
    private $iss = JwtEnum::ISS;
    //用户数据
    //private $userInfo;

    //获取token
    public function getJwtToken($userInfo,$rules){
        $payload = [
            'iss' => $this->iss,
            //过期时间
            //'exp' => time() + 60 ,
            //签发时间
            'iat' => time(),
            'userinfo' =>  [
                'id'        => $userInfo['id'],
                'username'  => $userInfo['username'],
                'logintime' => date('Y-m-d H:i:s', $userInfo['logintime']),
                'loginip'   => $userInfo['loginip'],
                'nickname'  => $userInfo['nickname'],
                'image'     => $userInfo['image'],
                'rules' => explode(',', $rules),
            ],
        ];

        return JWTS::encode($payload, $this->key);
    }

    //验证token
    public function checkJwtToken($jwt)
    {
        try {
            //当前时间减去60，把时间留点余地
            JWTS::$leeway = 60;
            //HS256方式，这里要和签发的时候对应
            $decoded = JWTS::decode($jwt, $this->key,array('HS256'));
            //强制返回数组
            $arr = (array)$decoded;
            $arr['code']=1;
            $arr['time']=time();
            //返回数据
            return (array) $arr['userinfo'];

        } catch(\Firebase\JWT\SignatureInvalidException $e) {
            //签名不正确
            throw new AuthenticationException(
                [
                'code'=>403,
                'msg'=>'签名不正确',
                'errorCode'=>4003,
                    ]
            );
        }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            throw new AuthenticationException(
                [
                    'code'=>402,
                    'msg'=>'token失效请重新登录',
                    'errorCode'=>4002,
                ]
            );
        }catch(\Firebase\JWT\ExpiredException $e) {
            // token过期
            throw new AuthenticationException(
                [
                    'code'=>401,
                    'msg'=>'token过期请重新登录',
                    'errorCode'=>4001,
                ]
            );
        }catch(\Exception $e) {
            //其他错误
            throw new AuthenticationException();
        }

        //return (array) JWTS::decode($jwt, $this->key,array('HS256'));
    }

}